#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <cstdio>
#include <string>
#include <strings.h>
#include <unistd.h>

void Usage(char *proc)
{
  std::cout << "\n\tUsage: " << proc << " serverip serverport" << std::endl;
}

int main(int argc, char *argv[])
{
  if (argc != 3)
  {
    Usage(argv[0]);
    exit(0);
  }

  std::string serverip = argv[1];
  uint16_t serverport = std::stoi(argv[2]);
  // 创建一个套接字
  int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
  if (sockfd < 0)
  {
    std::cout << "sockfd create failed" << std::endl;
    return 1;
  }

  struct sockaddr_in server;
  bzero(&server, sizeof(server));
  server.sin_family = AF_INET;
  server.sin_addr.s_addr = inet_addr(serverip.c_str());
  server.sin_port = htons(serverport);
  socklen_t len = sizeof(server);

  std::string buffer;
  char message[1024];
  while (true)
  {
    // 发送消息到服务器
    std::cout << "Please Enter@ ";
    getline(std::cin, buffer);

    sendto(sockfd, buffer.c_str(), buffer.size(), 0, (struct sockaddr *)&server, len);

    struct sockaddr_in client;
    socklen_t len = sizeof(client);
    // 接收服务器返回的消息
    ssize_t rcv = recvfrom(sockfd, message, 1023, 0, (struct sockaddr *)&client, &len);
    if (rcv > 0)
    {
      message[rcv] = 0;
      std::cout << message << std::endl;
    }
  }
  close(sockfd);

  return 0;
}